package TTEST;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;

import panel.CommandPanel;

import Files.File_;
import a.SwingShell;
import a._AdvancedVerifier;
import a._ConnectionThread;
import a._EnterSomethingDialog;
import a.jframe.InternalFrame;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.KnownHosts;
import ch.ethz.ssh2.Session;
 
class __TerminalDialog //extends JTabbedPane
{
	private static final long serialVersionUID = 1L;

	JPanel botPanel;
	JButton logoffButton;
	JTextArea terminalArea;

	Session sess;
	InputStream in;
	OutputStream out;

	int x, y;
	class RemoteConsumer extends Thread
	{
		char[][] lines = new char[y][];
		int posy = 0;
		int posx = 0;

		private void addText(byte[] data, int len)
		{
			for (int i = 0; i < len; i++)
			{
				char c = (char) (data[i] & 0xff);
				if (c == 8) // Backspace, VERASE
				{
					if (posx < 0)
						continue;
					posx--;
					continue;
				}
				if (c == '\r')
				{
					posx = 0;
					continue;
				}
				if (c == '\n')
				{
					posy++;
					if (posy >= y)
					{
						for (int k = 1; k < y; k++)
							lines[k - 1] = lines[k];
						posy--;
						lines[y - 1] = new char[x];
						for (int k = 0; k < x; k++)
							lines[y - 1][k] = ' ';
					}
					continue;
				}

				if (c < 32)
				{
					continue;
				}
				if (posx >= x)
				{
					posx = 0;
					posy++;
					if (posy >= y)
					{
						posy--;
						for (int k = 1; k < y; k++)
							lines[k - 1] = lines[k];
						lines[y - 1] = new char[x];
						for (int k = 0; k < x; k++)
							lines[y - 1][k] = ' ';
					}
				}
				if (lines[posy] == null)
				{
					lines[posy] = new char[x];
					for (int k = 0; k < x; k++)
						lines[posy][k] = ' ';
				}
				lines[posy][posx] = c;
				posx++;
			}
			StringBuffer sb = new StringBuffer(x * y);
			for (int i = 0; i < lines.length; i++)
			{
				if (i != 0)
					sb.append('\n');
				if (lines[i] != null)
				{
					sb.append(lines[i]);
				}
			}
			setContent(sb.toString(),aa);
		}
		 
		JTextArea aa;
		public RemoteConsumer(JTextArea pp)
		{
			aa=pp;
			//aa.setPreferredSize(new Dimension(50,50));
		}
		public void run()
		{
			byte[] buff = new byte[8192];
			try
			{
				while (true)
				{
					int len = in.read(buff);
					if (len == -1)
						return;
					addText(buff, len);
				}
			}
			catch (Exception e)
			{
			}
		}
	}
	public __TerminalDialog(MyInternalFrame pp, String title, Session sess, int x, int y) throws IOException
	{
		//super(parent, title, true);

		this.sess = sess;

		in = sess.getStdout();
		out = sess.getStdin();

		this.x = x;
		this.y = y;
		Font f = new Font("Monospaced", Font.PLAIN, 12);

		//terminalArea = new JTextArea(y, x);
	/*	terminalArea.setSize(200, 200);
		terminalArea.setFont(f);
		terminalArea.setBackground(Color.BLACK);
		terminalArea.setForeground(Color.ORANGE);
		terminalArea.setCaretColor(Color.BLACK);*/
		KeyAdapter kl = new KeyAdapter()
		{
			public void keyTyped(KeyEvent e)
			{
				int c = e.getKeyChar();

				try
				{
					out.write(c);
				}
				catch (IOException e1)
				{
				}
				e.consume();
			}
		};

	//	terminalArea.addKeyListener(kl);
		//botPanel = new JPanel(new BorderLayout());
		
		MouseListener mouseListener = new MouseAdapter() {
		    public void mouseClicked(MouseEvent e) {
		       System.out.println("zzzzzzzzzzzzzzz"+e.getSource());
		       String example = "This is only an example";
		       example="";
		       for(Object key:File_.common_map_commands.keySet())
		       {
		    	   System.out.println(((JList)e.getSource()).getSelectedValue().toString()+" "+key);
		    	   if(
		    			   ((JList)e.getSource()).getSelectedValue().equals(key))//==key)
		    	   {
		    		   example+=File_.common_map_commands.get(key);break;
		    	   }
		    	   
		       }
		       byte[] bytes = example.getBytes();
		       try {
				out.write(bytes);
			} catch (IOException e1) {
				//e1.printStackTrace();
			}
		    }
		};

		GridLayout experimentLayout = new GridLayout(1,0);
		//botPanel.setLayout(experimentLayout);
			JList		listbox=new JList();listbox.setPreferredSize(new Dimension(50,600));
			DefaultListModel df= new DefaultListModel ();
			
			Map<String,String> c= new File_().readF(0);
			if (!c.isEmpty()){
				df.clear();
				 
			Set<String> test = c.keySet();
			for (String key : test) {
				df.addElement(c.get(key));
			    }
			}
			listbox.setModel(df);		listbox.addMouseListener(mouseListener);
		
		JButton button2 = new JButton("Button 1 (PAGE_START)");
		
		
		
		/*botPanel.add(terminalArea,BorderLayout.CENTER);
		botPanel.add(new JButton("TEST"),BorderLayout.LINE_START);*/
	//	GridLayout layout = new GridLayout(0,3);
	//	JPanel d=new JPanel(layout);
	
	//	JButton button3 = new JButton("Button 2 (CENTER)");
		//botPanel.add(button3, BorderLayout.CENTER);
		//botPanel.add(d, BorderLayout.CENTER);
		SwingShell.arraycomandpanel.put("labtest", new CommandPanel("Test"));
	//	botPanel.add(arraycomandpanel.get("labtest"),BorderLayout.CENTER);
		
		//////////////////////////////////
	//	pp.tabbedPane.addTab( "Page 12", botPanel );
	//	pp.add(pp.tabbedPane);
		//////////////////////////////////
		pp.botPanel.add(new JButton("TEST"),BorderLayout.LINE_START);
		new RemoteConsumer(terminalArea).start();
		//new RemoteConsumer(terminalArea).start();
	}

	public void setContent(String lines,JTextArea pole)
	{
		pole.setText(lines);
		//terminalArea1.setText(lines);
	}
}
class __ConnectionThread extends Thread
{
	String hostname,username;
	MyInternalFrame o;
	public __ConnectionThread(MyInternalFrame p,String hostname, String username)
	{
		this.o=p;
		this.hostname = hostname;
		this.username = username;
	}
	public __ConnectionThread(String hostname, String username)
	{
		this.hostname = hostname;
		this.username = username;
	}

	public void run()
	{
		Connection conn = new Connection(hostname);
		try
		{
			String[] hostkeyAlgos = o.database.getPreferredServerHostkeyAlgorithmOrder(hostname);
			if (hostkeyAlgos != null)
				conn.setServerHostKeyAlgorithms(hostkeyAlgos);

			conn.connect(new _AdvancedVerifier());
			boolean enableKeyboardInteractive = true,enableDSA = true,enableRSA = true;
			String lastError = null;
			while (true)
			{
				if ((enableDSA || enableRSA) && conn.isAuthMethodAvailable(username, "publickey"))
				{
					if (enableDSA)
					{
						File key = new File(o.idDSAPath);
						if (key.exists())
						{
							/*boolean res = true;
							if (res == true)*/
								break;
							/*lastError = "DSA authentication failed.";*/
						}
						enableDSA = false; // do not try again
					}
					if (enableRSA)
					{
						File key = new File(o.idRSAPath);
						if (key.exists())
						{
							/*boolean res = true;
							if (res == true)*/
								break;
							/*lastError = "RSA authentication failed.";*/
						}
						enableRSA = false; // do not try again
					}
					continue;
				}
				if (conn.isAuthMethodAvailable(username, "password"))
				{
					boolean res = conn.authenticateWithPassword(username, "log");
					if (res == true)
						break;
					lastError = "Password authentication failed."; // try again, if possible
					continue;
				}
				throw new IOException("No supported authentication methods available.");
			}
			Session sess = conn.openSession();
			int x_width = 130;
			int y_width = 40;
			sess.requestPTY("dumb", x_width, y_width, 0, 0, null);
			sess.startShell();
			//TerminalDialog td = new TerminalDialog(_frame, username + "@" + hostname, sess, x_width, y_width);
			__TerminalDialog td = new __TerminalDialog(o,username + "@" + hostname, sess, x_width, y_width);
		//	td.setSize(200, 100);
		//	SwingShell.loginPanel.add(td);
		}
		catch (IOException e)
		{
			JOptionPane.showMessageDialog(o, "Exception: " + e.getMessage());
		}
	}
}
public class MyInternalFrame extends JInternalFrame {
	
	  static final String knownHostPath = "~/.ssh/known_hosts",//;
	    /*static final String*/ idDSAPath = "~/.ssh/id_dsa",//;
	    /*static final String*/ idRSAPath = "~/.ssh/id_rsa";
	    
	    
	static KnownHosts database = new KnownHosts();
    static int openFrameCount = 0;
    static final int xOffset = 30, yOffset = 30;
    int x_width = 90,//;
    /*int*/ y_width = 30;
   // static JTabbedPane tabbedPane;
    JTextArea terminalArea = new JTextArea(x_width, y_width);
    Map<Integer,__ConnectionThread> mapka=new HashMap<Integer, __ConnectionThread>();
    JPanel botPanel;
    public MyInternalFrame() {
        super("Document #" + (++openFrameCount), 
              true, //resizable
              true, //closable
              true, //maximizable
              true);//iconifiable
        botPanel = new JPanel(new BorderLayout());
        Font f = new Font("Monospaced", Font.PLAIN, 12);
    	terminalArea.setSize(200, 200);
		terminalArea.setFont(f);
		terminalArea.setBackground(Color.BLACK);
		terminalArea.setForeground(Color.ORANGE);
		terminalArea.setCaretColor(Color.BLACK);
		
      /*   tabbedPane = new JTabbedPane();
        tabbedPane.setSize(200,200);
        tabbedPane.add(terminalArea);*/
        setSize(300,300);
        getContentPane().add(new JButton("Button"),BorderLayout.PAGE_START);
        getContentPane().add(terminalArea,BorderLayout.CENTER);
        JPanel anotherPanel=new JPanel(new BorderLayout());
        anotherPanel.add(new JButton("TEST_P_S"),BorderLayout.PAGE_START);
        anotherPanel.add(new JButton("TEST"),BorderLayout.CENTER);
        anotherPanel.add(new JButton("TEST_L"),BorderLayout.LINE_START);
        anotherPanel.add(new JButton("TEST_R"),BorderLayout.LINE_END);
        anotherPanel.add(new JButton("TEST_P_E"),BorderLayout.PAGE_END);
        getContentPane().add(anotherPanel,BorderLayout.PAGE_START);
        
        
        JPanel commandPanel=new JPanel(new BorderLayout());
        commandPanel.add(new JButton("TEST_PAGE_END"),BorderLayout.PAGE_END);
        getContentPane().add(commandPanel,BorderLayout.PAGE_END);
        //getContentPane().add(botPanel);
      //  getContentPane().add(tabbedPane);
      //  getContentPane().add(new JButton("a"));getContentPane().add(new JButton("b"));
        setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
        __ConnectionThread ct = new __ConnectionThread(this,"10.41.93.147",
        "log");
        mapka.put(1, ct);
        mapka.get(1).start();
    }
}
